package org.apache.struts.ehr.medical_records.action;

import java.util.Map;

import org.apache.axiom.om.OMElement;
import org.apache.struts.ehr.medical_records.model.HL7Message;
import org.apache.struts.ehr.medical_records.model.Query;
import org.apache.struts.ehr.medical_records.model.ReplyMessage;

import com.earogya.Constants;
import com.earogya.communicate.Communicator;
import com.earogya.logic.medical_records.CreateADTA08;
import com.earogya.logic.medical_records.CreateQRYA19;
import com.earogya.logic.medical_records.ParseReply;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
/***
 * This class is the struts action to query details
 * Not needed any more
 * @author Chamendri
 *
 */
public class QueryDetailsAction extends ActionSupport{
	
	private Query query;
	private HL7Message message;
	private ReplyMessage replyMessage;
	
	public Query getQuery() {
		return query;
	}
	public void setQuery(Query query) {
		this.query = query;
	}
	public HL7Message getMessage() {
		return message;
	}
	
	public ReplyMessage getReplyMessage() {
		return replyMessage;
	}
	
	/**
	 * Overrides execute method in ActionSupport interface
	 * Creates a QRY A19 message and send to the back end.
	 */
	public String execute() throws Exception {
		Map<String, Object> session=ActionContext.getContext().getSession();
		replyMessage=new ReplyMessage();
		replyMessage.setMessage(Constants.EMPTY);
		CreateQRYA19 createMessage=new CreateQRYA19(query);
		String msg=createMessage.createMessage(Constants.SENDING_FACILITY);
		message=new HL7Message();
		if(!msg.equals(null)){
			Communicator c=new Communicator();
			String reply=c.sendMessage(msg);
			if(!reply.equals(Constants.NO_REPLY)){
				ParseReply parse=new ParseReply();
				replyMessage=(ReplyMessage)parse.parseMessage(reply);
			}
		}
		else{
			message.setMessage(Constants.EMPTY);
		}
		return SUCCESS;
	}
	
	/**
	 * overrides the input fields in query form
	 */
	public void validate(){
		if(query.getPatientId().length()==0){
			addFieldError( "query.patientId", "Patient ID required" );
		}
		else if(!this.isInteger(query.getPatientId())){
			addFieldError( "query.patientId", "Incorrect patient ID format." );
		}
		if(query.getSearch_type().length()==0){
			addFieldError( "query.search_type", "Search category required." );
		}
	}
	
	/**
	 * Check if the given string is an integer
	 * @param value
	 * @return true if the given string is an integer
	 */
	private Boolean isInteger(String value){
		Boolean isInteger=false;
		try{
			int intValue=Integer.parseInt(value);
			isInteger=true;
		}catch(NumberFormatException e){
			isInteger=false;
		}
		return isInteger;
	}
}
